package net.feixue.engine.atomjob;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * Created by zxxiao on 14/12/31.
 */
public class EngineJob {

    private List<EngineTask> taskList;

    private Set<Long> taskIdSet;

    private EngineTaskNotify taskNotify;

    private EngineJobNotify jobNotify;

    private EngineFuture future;

    public EngineJob() {
        taskList = new LinkedList<>();
        taskIdSet = new ConcurrentSkipListSet<>();
        taskNotify = new EngineTaskNotify() {
            @Override
            public void doNotify(long id) {
                taskIdSet.remove(id);
                if (taskIdSet.size() == 0) {
                    if (jobNotify != null) {
                        jobNotify.doNotify();
                    } else if (future != null) {
                        future.setFinish(true);
                    }
                }
            }
        };
    }

    protected void setJobNotify(EngineJobNotify jobNotify) {
        this.jobNotify = jobNotify;
    }

    protected List<EngineTask> getTaskList() {
        return taskList;
    }

    protected void setFuture(EngineFuture future) {
        this.future = future;
    }

    public void addTask(EngineTask task) {
        task.setTaskNotify(taskNotify);

        taskIdSet.add(task.getId());

        taskList.add(task);
    }
}
